import { useAppStore } from '@/store/modules/app'
import { ref } from 'vue'
import { Dictionary, DictionaryItem, SelectOption } from '@/api/common/types'
import { getDictionaryListApi } from '@/api/common'

const appStore = useAppStore()

export enum TagTypeEnum {
  DEFAULT = '',
  SUCCESS = 'success',
  INFO = 'info',
  WARNING = 'warning',
  DANGER = 'danger'
}
const dictionaryItem = ref<DictionaryItem>({
  itemName: '',
  itemValue: '',
  tag: ''
})
export const dictionaryItemName = (type: string, value: string) => {
  const dictionaryList = appStore.getDictionaryList
  if (dictionaryList) {
    dictionaryList.map((dictionary) => {
      if (dictionary.dictionaryCode == type) {
        dictionary.dictionaryItemList.map((item) => {
          if (item.itemValue == value) {
            dictionaryItem.value = Object.assign(dictionaryItem, item)
          }
        })
      }
    })
    return dictionaryItem.value.itemName
  }
}

export const dictionaryItemTag = (type: string, value: string) => {
  const dictionaryList = appStore.getDictionaryList
  if (dictionaryList) {
    dictionaryList.map((dictionary) => {
      if (dictionary.dictionaryCode == type) {
        dictionary.dictionaryItemList.map((item) => {
          if (item.itemValue == value) {
            dictionaryItem.value = Object.assign(dictionaryItem, item)
          }
        })
      }
    })
    return TagTypeEnum[dictionaryItem.value.tag]
  }
}

const getDictionaryList = async () => {
  const res = await getDictionaryListApi()
  if (res) {
    appStore.setDictionaryList(res.data)
  }
  return res.data
}

export const getDictionarySelectOptionList = (type: string) => {
  let dictionaryList: Dictionary[] = appStore.getDictionaryList
  if (!dictionaryList || dictionaryList.length <= 0) {
    getDictionaryList().then((res) => {
      dictionaryList = res
    })
  }
  let selectOptionList: SelectOption[] = []
  dictionaryList.forEach((dictionary) => {
    if (dictionary.dictionaryCode == type && dictionary.dictionaryItemList) {
      selectOptionList = dictionary.dictionaryItemList.map((item) => {
        return {
          label: item.itemName,
          value: item.itemValue
        }
      })
    }
  })
  return selectOptionList
}
